package com.caisejingyu.whales.common.ui;

import android.app.Activity;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.LifecycleOwner;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

import com.caisejingyu.whales.common.BaseApplication;
import com.caisejingyu.whales.common.utils.WindowDensityUtil;
import com.caisejingyu.whales.mediator.main.service.MediatorServiceFactory;

import java.lang.ref.WeakReference;
import java.util.List;


/**
 * 说明：初始化的WrapActivityLifecycleCallback
 * 一束光线：1050189980 2018/8/14
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public class InitActivityLifecycleCallback extends WrapActivityLifecycleCallbacks {

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        injectInit(activity, savedInstanceState);
        injectAddLifecycleObservers(activity);
        injectRegisterFragmentLifecycleCallbacks(activity);
    }

    @Override
    public void onActivityResumed(Activity activity) {
        BaseApplication.setLastResumeActivityReference(new WeakReference<>(activity));
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        injectRemoveLifecycleObservers(activity);
    }

    protected void injectInit(Activity activity, Bundle savedInstanceState) {
        // 屏幕适配
        WindowDensityUtil.setCustomDensity(activity, activity.getApplication());
       
    }

    protected void injectAddLifecycleObservers(Activity activity) {
        // 为服务添加生命周期观察
        if (activity instanceof LifecycleOwner) {
            BaseApplication.setLastLifecycleOwner((LifecycleOwner) activity);
            Lifecycle lifecycle = BaseApplication.getLastLifecycleOwner().getLifecycle();
            List<LifecycleObserver> lifecycleObservers = MediatorServiceFactory.getInstance().getAll(LifecycleObserver.class);
            for (LifecycleObserver observer : lifecycleObservers) {
                lifecycle.addObserver(observer);
            }
        }
    }

    protected void injectRemoveLifecycleObservers(Activity activity) {
        // 去除服务的生命周期观察
        if (activity instanceof LifecycleOwner) {
            BaseApplication.setLastLifecycleOwner(null);
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            List<LifecycleObserver> lifecycleObservers = MediatorServiceFactory.getInstance().getAll(LifecycleObserver.class);
            for (LifecycleObserver observer : lifecycleObservers) {
                lifecycle.removeObserver(observer);
            }
        }
    }

    protected void injectRegisterFragmentLifecycleCallbacks(Activity activity) {
        if (activity instanceof FragmentActivity) {
            ((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(new InitFragmentLifecycleCallback(), true);
        }
    }
}
